// 1. 导入 http 模块
const http = require('http');
const db = require('./m.js');
const dayjs = require('dayjs');
// 2. 创建 web 服务器实例
const server = http.createServer();

// 3. 启动服务器
server.listen(8848, () => {
	console.log('my server start work');
});

// 4. 为服务器实例绑定 request 事件，监听客户端的请求
server.on('request', (request, response) => {
	// 设置响应的内容为JSON
	response.setHeader('Content-Type', 'application/json; charset=utf-8');
	response.setHeader('Access-Control-Allow-Origin', '*');
	// 不能直接响应 对象/数组 需要转为字符串
	if (request.method === 'GET' && request.url === '/api/students') {
		response.end(JSON.stringify(db.studentsInfo()));
	} else if (request.method === 'GET' && request.url === '/api/luckyStudent') {
		response.end(JSON.stringify(db.luckyStudent()));
	} else {
		response.statusCode = 404;
		response.end('404 not found');
	}
});
